//
// Created by alexa on 5/13/2024.
//

#include "SoldiersService.h"
#include "../../exceptions/EntityNotFound.h"

Soldier *SoldiersService::getById(string id) {
    Soldier *soldier = repository.findById(id);
    if (!soldier) {
        throw EntityNotFound("Soldier with this id wasn't found.");
    }
    return soldier;
}

vector<Soldier *> SoldiersService::getAll() {
    return repository.findAll();
}

void SoldiersService::deleteOne(string id) {
    Soldier *soldier = getById(id);
    MaintenanceCrew* crew = crewsService->findBySoldierId(id);
    if (crew) {
        crew->removeSoldierId(id);
        crewsService->saveCrew(crew);
    }
    repository.deleteOne(soldier);
}

Soldier *SoldiersService::createOne(string firstname, string surname, string rank, Specialization specialization) {
    Soldier *soldier = new Soldier(firstname, surname, rank, specialization);
    repository.save(soldier);
    return soldier;
}

vector<Soldier *> SoldiersService::getManyByIds(vector<string> ids) {
    vector<Soldier *> soldiers;
    for (const auto &id: ids) {
        try {
            soldiers.push_back(getById(id));
        } catch (EntityNotFound &pass) {}
    }
    return soldiers;
}

void SoldiersService::saveSoldier(Soldier *soldier) {
    repository.save(soldier);
}

void SoldiersService::setCrewsService(CrewsService *crewsService) {
    this->crewsService = crewsService;
}
